package com.rfid.a252robot.task;

import android.text.TextUtils;

import com.rfid.a252robot.event.BorrowEvent;
import com.rfid.a252robot.event.RestoreEvent;
import com.rfid.a252robot.net.BookLibApi;
import com.rfid.a252robot.net.BoxLibApi;
import com.rfid.a252robot.net.bean.BookInfoRespon;
import com.rfid.a252robot.net.bean.UploadBook;
import com.rfid.acs.bean.BookBean;
import com.rfid.acs.net.bean.RestoreBookBean;
import com.rfid.common.log.LogUtils;
import com.rfid.db.bean.Book;
import com.rfid.db.bean.FailBook;
import com.rfid.manager.BookManager;
import com.rfid.manager.DBManager;
import com.rfid.manager.DoorBoxManager;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class CheckFailTask extends TimerTask {

    Executor mExecutor = Executors.newSingleThreadExecutor();
    @Override
    public void run() {
        LogUtils.v("CheckFailTask start");
        try {
            List<FailBook> books = DBManager.getFailBooks();
            for (FailBook failBook : books) {
                if (failBook.getBorrow()) {
                    reborrow(failBook);
                } else {
                    reRestore(failBook);
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            List<Book> books1 = DBManager.getBooks();
            for (Book book : books1) {
                if (TextUtils.isEmpty(book.getIsbn())) {
                    queryIsbn(book);
                }
            }
        } catch (Exception e) {
            LogUtils.e(e);
        }
    }

    private void queryIsbn(Book book) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BookInfoRespon info = BookLibApi.INSTANCE.getBookInfo(book.getBarcode());
                    List<BookInfoRespon.DataBeanX.DataBean.ItemsBean> itemsBeans = info.getData().getData().getItems();
                    if (itemsBeans != null && itemsBeans.size() > 0) {
                        List<BookInfoRespon.DataBeanX.DataBean.ItemsBean.IdentifiersBean> ids = itemsBeans.get(0).getIdentifiers();
                        if (ids != null&&ids.size() > 0) {
                            String isbn = ids.get(0).getValue();
                            book.setIsbn(isbn);
                            DBManager.updateBook(book);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void reRestore(FailBook failBook) {
        String barcode = failBook.getBarcode();
        if (DBManager.getBook(barcode) == null) {
            DBManager.deleteFailBook(failBook);
            return;
        }
        LogUtils.v("reRestore = " + failBook.getBarcode());
        BookManager.INSTANCE.restoreBook(barcode)
                .observeOn(Schedulers.io())
                .map(new Function<RestoreBookBean, Book>() {
                    @Override
                    public Book apply(RestoreBookBean restoreBookBean) throws Exception {
                        System.out.println("restoreBookBean = " + restoreBookBean);
                        Book book1 = DBManager.getBook(barcode);
                        System.out.println("book1 = " + book1);
                        if (book1 != null) {
                            if (restoreBookBean.isSuccess()) {
                                book1.setCanBorrow(true);
                            }
                            book1.setName(restoreBookBean.getBookName());
                            DBManager.updateBook(book1);
                        }
                        DBManager.deleteFailBook(failBook);
                        try {
                            BoxLibApi.INSTANCE.uploadBook(book1, UploadBook.TYPE_NORMAL);
                        } catch (Exception e) {
                            LogUtils.e(e);
                        }
                        return book1;
                    }
                }).subscribe(new Consumer<Book>() {
                    @Override
                    public void accept(Book o) throws Exception {
                        if (o != null) {
                            EventBus.getDefault().post(new RestoreEvent(o));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        LogUtils.e(throwable);
                    }
                });

    }

    private void reborrow(FailBook book) {
        String barcode = book.getBarcode();
        if (DBManager.getBook(barcode) != null) {
            DBManager.deleteFailBook(book);
            return;
        }
        LogUtils.v("reborrow = " + book.getBarcode());
        BookManager.INSTANCE.borrowBook(book.getBarcode(),book.getReader(),book.getPwd())
                .observeOn(Schedulers.single())
                .map(new Function<BookBean, BookBean>() {
                    @Override
                    public BookBean apply(BookBean bookBean) throws Exception {
                        try {
                            System.out.println(Thread.currentThread().getName());
                            BoxLibApi.INSTANCE.deleteBook(Book.convert(book), UploadBook.TYPE_NORMAL);
                        } catch (Exception e) {
                            LogUtils.e(e);
                        }
                        return bookBean;
                    }
                })
                .subscribe(new Consumer<BookBean>() {
                    @Override
                    public void accept(BookBean bookBean) throws Exception {
                        DBManager.deleteFailBook(book);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }
}
